package jmine.tec.rpc.common.serialization.json;

import jmine.tec.json.JSON;
import jmine.tec.json.JSONObject;
import jmine.tec.json.JSONString;
import jmine.tec.rpc.RPCMessages;
import jmine.tec.rpc.common.RPCException;
import bancosys.tec.utils.reflection.ReflectionUtils;

/**
 * Conversor de JSON para Java e vice-versa
 * 
 * @author lundberg
 */
public class JSONClassConverter extends AbstractJSONObjectConverter implements JSONConverterStrategy {

    /**
     * {@inheritDoc}
     */
    public boolean matchesJava(Object object) {
        return object instanceof Class && !((Class) object).isArray();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected JSON objectType() {
        return new JSONString("class");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object instantiate(JSONConversionContext context, JSON json) {
        try {
            return ReflectionUtils.findClass(json.getProperty("value").toString(), this.getClass().getClassLoader());
        } catch (ClassNotFoundException e) {
            throw new RPCException(RPCMessages.CLASS_NOT_FOUND.create(json.getProperty("value")), e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillObject(JSONConversionContext context, JSON json, Object object) {
        // OK
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void fillJSON(JSONConversionContext context, Object object, JSONObject json) {
        json.setProperty("value", new JSONString(((Class) object).getCanonicalName()));
    }
}
